import os
import json

from python.coin.tool.strat_monitor.util.monitor_util import get_active_strategy
from xunkemgmt.support.accounting.logic.query_request import get_all_application_view_df
from coin.support.accounting.logic.key_util import get_key_file_impl
from coin2.service.order_detector.influxdb import InfluxdbTakeOut

def get_exchange_detector_info(key_root: str) -> dict:
  filter_strategy_list = ["lm_agg2_coincheck_spot_1"]
  filter_exchange_list = ["Uniswap", "Lmaxdigital"]
  
  queue_need_native_symol_exchange_list = ["Mexc", "Binance"]
  db = InfluxdbTakeOut()
  
  try:
      strat_list = get_active_strategy()
      df_acct = get_all_application_view_df(True)
  except Exception as e:
    print("get_active_strategy err ", e)
    return [], []

  df_acct['strategy_name'] = df_acct['strategy_name_x']
  del df_acct['strategy_name_y']
  del df_acct['strategy_name_x']

  strat_info_list = []
  ignore_strategy_list = []
  for strat in strat_list:
    acct = df_acct.loc[df_acct['strategy_name'].str.match(strat)]
    for _, row_acct in acct.iterrows():
      if row_acct['exchange'] in filter_exchange_list:
        continue
      
      if row_acct["exchange"] != "Binance":
        continue
      
      if row_acct["strategy_name"] in filter_strategy_list:
        ignore_strategy_list.append(row_acct["strategy_name"])
        continue
      
      try:
        key_path = get_key_file_impl(key_root, "view_key.json", row_acct['market_type'], row_acct['exchange'], row_acct['owner'], row_acct["api_version"], key_type="view")
      except Exception as e:
        print("ignore ", row_acct, e)
        ignore_strategy_list.append(row_acct["strategy_name"])
        continue

      strat_info = dict(exchange=row_acct['exchange'],
                        market_type=row_acct['market_type'],
                        strategy_name=row_acct['strategy_name'],
                        owner=row_acct['owner'],
                        api_version= row_acct['api_version'],
                        key_path = key_path,
                        )

      if not os.path.isfile(key_path):
        print("ignore ", strat_info,  "key_path not exist")
        ignore_strategy_list.append(row_acct["strategy_name"])
        continue
      
      try:
        exchange = strat_info["exchange"]
        if exchange in queue_need_native_symol_exchange_list:
          native_symbols = db.get_native_symbol_by_strategy_name(strat_info["strategy_name"], exchange)
          strat_info["native_symbols"] = native_symbols
      except Exception as e:
        print("ignore ",  strat_info, e)
        ignore_strategy_list.append(row_acct["strategy_name"])
        continue
      strat_info_list.append(strat_info)

  strat_info_list.sort(key=lambda x: x["exchange"])
  return strat_info_list, ignore_strategy_list


def need_native_symbol_to_query_open_order(exchange)->bool:
    exchange_list = ["Mexc"]
    return exchange in exchange_list
